from typing import Any, Coroutine

import cv2
import numpy as np
from deepface import DeepFace

# 将图片路径转换为np.ndarray
async def image_path_to_ndarray(image_path):
    print(image_path)
    return cv2.imread(image_path)

# 将图片文件转换为np.ndarray
async def image_file_to_ndarray(image_file):
    contents = await image_file.read()  # 使用 await 读取文件内容
    return cv2.imdecode(np.frombuffer(contents, np.uint8), cv2.IMREAD_COLOR)


# 根据图片文件进行人脸检测
async def deepface_analyze_file(image_file):
    # 将图片文件转换为np.ndarray
    image_ndarray = await image_file_to_ndarray(image_file)
    # 进行人脸检测
    result = await deepface_analyze_ndarray(image_ndarray)
    return result

# 根据图片路径进行人脸检测
async def deepface_analyze_path(file_path):
    # 进行图片分析
    image_ndarray= await image_path_to_ndarray(file_path)
    result = await deepface_analyze_ndarray(image_ndarray)
    return result


async def deepface_analyze_ndarray(image_ndarray):
    result = DeepFace.analyze(image_ndarray, actions=['emotion'])
    # 将结果转换为 JSON 可序列化的格式
    serializable_result = convert_to_serializable(result)
    return serializable_result

def convert_to_serializable(result):
    if isinstance(result, dict):
        return {k: convert_to_serializable(v) for k, v in result.items()}
    elif isinstance(result, list):
        return [convert_to_serializable(v) for v in result]
    elif isinstance(result, np.ndarray):
        return result.tolist()
    elif isinstance(result, np.number):
        return result.item()
    else:
        return result